const { api } = require("../../utils/api.js");

// 发现页面
Page({
  data: {
    categories: [{ id: "breakfast", name: "早餐" }],
    selectedCategory: "breakfast",
    recipeList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showFilter: false,
    searchKeyword: "", // 搜索关键词
    isSearching: false, // 是否正在搜索
    searchHistory: [], // 搜索历史
    showSearchResult: false, // 是否显示搜索结果
    searchResultCache: {}, // 搜索结果缓存
    statusBarHeight: 20, // 状态栏高度，默认20
  },

  // 搜索定时器，用于防抖
  searchTimer: null,

  onLoad() {
    // 获取系统信息，设置状态栏高度
    try {
      const systemInfo = wx.getSystemInfoSync();
      this.setData({
        statusBarHeight: systemInfo.statusBarHeight || 20
      });
      console.log("状态栏高度:", systemInfo.statusBarHeight);
    } catch (e) {
      console.error("获取系统信息失败:", e);
    }
    
    // 检查登录状态
    const token = wx.getStorageSync("token");
    if (!token) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
        duration: 2000,
        success: () => {
          setTimeout(() => {
            wx.redirectTo({
              url: "/pages/index/index",
            });
          }, 1000);
        },
      });
      return;
    }

    // 页面加载时的逻辑
    console.log("发现页面加载成功");
    this.getCategories();
    this.getRecipeList();

    // 获取搜索历史
    this.getSearchHistory();
  },

  onShow() {
    // 页面显示/切入前台时的逻辑
  },

  onHide() {
    // 页面隐藏/切入后台时的逻辑
    // 清除可能存在的定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  onPullDownRefresh() {
    // 下拉刷新时的逻辑
    this.getRecipeList();
  },

  // 防抖函数
  debounce(func, delay = 300) {
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    this.searchTimer = setTimeout(() => {
      func.apply(this);
    }, delay);
  },

  // 获取菜谱分类
  getCategories: function () {
    // 直接使用早餐分类，不再调用API
    this.setData({
      categories: [{ id: "breakfast", name: "早餐" }],
      selectedCategory: "breakfast" // 默认选中早餐分类
    });
  },

  // 获取菜谱列表
  getRecipeList: function (isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) {
      return;
    }

    this.setData({ loading: true });

    const page = isLoadMore ? this.data.page + 1 : 1;
    console.log("获取菜谱列表, 当前分类:", this.data.selectedCategory);

    api
      .getRecipeList(page, this.data.pageSize, this.data.selectedCategory)
      .then((res) => {
        if (res.code === 200 && res.data) {
          let list = res.data.list || [];
          const total = res.data.total || 0;

          // 如果API返回的数据不足，使用模拟数据
          if (list.length < 3) {
            console.log("使用模拟数据充实列表");
            const mockData = this.getMockRecipes();
            list = mockData;
          }

          this.setData({
            recipeList: isLoadMore ? [...this.data.recipeList, ...list] : list,
            page: page,
            hasMore: this.data.pageSize * page < total || list.length >= this.data.pageSize,
          });
        }
      })
      .catch((err) => {
        console.error("获取菜谱列表失败:", err);
        // 使用模拟数据
        const mockData = this.getMockRecipes();
        
        this.setData({
          recipeList: isLoadMore ? [...this.data.recipeList, ...mockData] : mockData,
          page: page,
          hasMore: false,
        });
      })
      .finally(() => {
        this.setData({ loading: false });
        wx.stopPullDownRefresh();
      });
  },

  // 获取模拟菜谱数据
  getMockRecipes: function () {
    return [
      {
        id: 1001,
        title: "营养早餐三明治",
        imageUrl: "/images/discovers/png/sanmingzhi.png",
        description: "健康美味的三明治，含有丰富的蛋白质和维生素",
        calories: 350,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1002,
        title: "水果燕麦早餐杯",
        imageUrl: "/images/discovers/png/yanmaishuiguozhou.png",
        description: "富含膳食纤维的燕麦，搭配新鲜水果，营养均衡的早餐选择",
        calories: 280,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1003,
        title: "牛油果全麦吐司",
        imageUrl: "/images/discovers/png/niuyouguo.png",
        description: "全麦面包搭配牛油果，美味健康的能量早餐",
        calories: 320,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1004,
        title: "蛋白能量早餐饼",
        imageUrl: "/images/discovers/png/danbaizhinengliangbing.png",
        description: "高蛋白早餐饼，晨跑前能量补充的理想选择",
        calories: 270,
        cookingTime: "15分钟",
        difficulty: "中等",
        category: "breakfast",
      },
      {
        id: 1005,
        title: "清爽蔬菜早餐沙拉",
        imageUrl: "/images/discovers/png/qingjiaoshishu.png",
        description: "低脂健康的蔬菜沙拉，搭配酸奶酱，清新美味的早餐",
        calories: 200,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1006,
        title: "香煎三文鱼早餐",
        imageUrl: "/images/discovers/png/sanwenyu.png",
        description: "富含omega-3的三文鱼配全麦面包，营养丰富的早餐搭配",
        calories: 450,
        cookingTime: "20分钟",
        difficulty: "中等",
        category: "breakfast",
      },
      {
        id: 1007,
        title: "鸡胸肉早餐卷",
        imageUrl: "/images/discovers/png/jixongrou.png",
        description: "健身人士的首选，高蛋白低脂早餐，搭配生菜和全麦饼",
        calories: 380,
        cookingTime: "20分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1008,
        title: "养生早餐粥",
        imageUrl: "/images/discovers/png/paigutang.png",
        description: "温暖滋补的早餐粥，搭配咸鸭蛋和青菜",
        calories: 300,
        cookingTime: "30分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1009,
        title: "水果酸奶早餐碗",
        imageUrl: "/images/discovers/png/shuiguoshala.png",
        description: "缤纷水果搭配酸奶，清新美味的轻食早餐",
        calories: 250,
        cookingTime: "10分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1010,
        title: "坚果能量早餐棒",
        imageUrl: "/images/discovers/png/nengliangbang.png",
        description: "自制能量棒，搭配各类坚果和蜂蜜，便携营养的早餐选择",
        calories: 320,
        cookingTime: "15分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1011,
        title: "草莓酸奶早餐杯",
        imageUrl: "/images/discovers/png/caomeisuannai.png",
        description: "新鲜草莓配希腊酸奶，美味营养的早餐搭配",
        calories: 220,
        cookingTime: "5分钟",
        difficulty: "简单",
        category: "breakfast",
      },
      {
        id: 1012,
        title: "全麦蔬菜早餐饼",
        imageUrl: "/images/discovers/png/binggan.png",
        description: "添加胡萝卜和菠菜的全麦饼，营养美味的早餐主食",
        calories: 280,
        cookingTime: "25分钟",
        difficulty: "中等",
        category: "breakfast",
      },
    ];
  },

  // 切换分类
  changeCategory: function (e) {
    const category = "breakfast"; // 固定为早餐分类
    console.log("切换分类:", category);

    this.setData(
      {
        selectedCategory: category,
        page: 1,
        hasMore: true,
        recipeList: [],
        searchKeyword: "",
        showSearchResult: false,
        isSearching: false,
      },
      () => {
        this.getRecipeList();
      }
    );
  },

  // 查看菜谱详情
  viewRecipeDetail: function (e) {
    const recipeId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/discover/recipe/detail/index?id=${recipeId}`,
    });
  },

  // 显示/隐藏筛选
  toggleFilter: function () {
    this.setData({
      showFilter: !this.data.showFilter,
    });
  },

  // 获取搜索历史
  getSearchHistory() {
    const history = wx.getStorageSync("recipeSearchHistory") || [];
    this.setData({ searchHistory: history });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    let history = wx.getStorageSync("recipeSearchHistory") || [];
    // 删除已存在的相同关键词
    history = history.filter((item) => item !== keyword);
    // 将新关键词添加到开头
    history.unshift(keyword);
    // 只保留最近10条记录
    history = history.slice(0, 10);
    wx.setStorageSync("recipeSearchHistory", history);
    this.setData({ searchHistory: history });
  },

  // 清空搜索历史
  clearSearchHistory() {
    wx.showModal({
      title: "提示",
      content: "确定要清空搜索历史吗？",
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync("recipeSearchHistory");
          this.setData({ searchHistory: [] });
        }
      },
    });
  },

  // 输入搜索关键词
  onSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({
      searchKeyword: keyword,
    });

    // 实时搜索，使用防抖减少请求次数
    if (keyword && keyword.length >= 2) {
      this.debounce(() => {
        this.setData(
          {
            showSearchResult: true,
            page: 1,
            hasMore: true,
            recipeList: [],
          },
          () => {
            this.searchRecipes();
          }
        );
      }, 500);
    } else if (!keyword) {
      this.setData({
        showSearchResult: false,
      });
    }
  },

  // 搜索框获取焦点
  onSearchFocus() {
    this.setData({
      isSearching: true,
    });
  },

  // 搜索框失去焦点
  onSearchBlur() {
    // 如果没有进行搜索且没有关键词，则退出搜索状态
    if (!this.data.showSearchResult && !this.data.searchKeyword) {
      this.setData({
        isSearching: false,
      });
    }
  },

  // 确认搜索
  onSearchConfirm(e) {
    const keyword = e.detail.value.trim();
    if (keyword) {
      // 首先检查缓存中是否有结果
      const cacheKey = `${keyword}_${this.data.selectedCategory}`;
      if (this.data.searchResultCache[cacheKey]) {
        console.log("使用缓存的搜索结果:", cacheKey);
        this.setData({
          searchKeyword: keyword,
          showSearchResult: true,
          isSearching: true,
          page: 1,
          recipeList: this.data.searchResultCache[cacheKey].list,
          hasMore: this.data.searchResultCache[cacheKey].hasMore,
        });
        this.saveSearchHistory(keyword);
      } else {
        this.setData(
          {
            searchKeyword: keyword,
            showSearchResult: true,
            isSearching: true,
            page: 1,
            hasMore: true,
            recipeList: [],
          },
          () => {
            this.saveSearchHistory(keyword);
            this.searchRecipes();
          }
        );
      }
    }
  },

  // 取消搜索
  cancelSearch() {
    this.setData(
      {
        searchKeyword: "",
        showSearchResult: false,
        isSearching: false,
        page: 1,
        hasMore: true,
      },
      () => {
        // 退出搜索状态后，重新加载菜谱列表
        this.getRecipeList();
      }
    );

    // 清除搜索防抖定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },

  // 点击搜索历史
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;

    // 首先检查缓存中是否有结果
    const cacheKey = `${keyword}_${this.data.selectedCategory}`;
    if (this.data.searchResultCache[cacheKey]) {
      console.log("使用缓存的搜索结果:", cacheKey);
      this.setData({
        searchKeyword: keyword,
        showSearchResult: true,
        isSearching: true,
        page: 1,
        recipeList: this.data.searchResultCache[cacheKey].list,
        hasMore: this.data.searchResultCache[cacheKey].hasMore,
      });
    } else {
      this.setData(
        {
          searchKeyword: keyword,
          showSearchResult: true,
          isSearching: true,
          page: 1,
          hasMore: true,
          recipeList: [],
        },
        () => {
          this.searchRecipes();
        }
      );
    }
  },

  // 搜索菜谱
  searchRecipes(isLoadMore = false) {
    if (this.data.loading || (!isLoadMore && !this.data.hasMore)) {
      return;
    }

    // 构建缓存 key
    const cacheKey = `${this.data.searchKeyword}_${this.data.selectedCategory}`;

    // 如果是加载更多并且缓存中存在结果，直接使用缓存结果
    if (
      isLoadMore &&
      this.data.searchResultCache[cacheKey] &&
      this.data.searchResultCache[cacheKey].page >= this.data.page + 1
    ) {
      const cachedResult = this.data.searchResultCache[cacheKey];
      this.setData({
        recipeList: [...this.data.recipeList, ...cachedResult.list],
        page: this.data.page + 1,
        hasMore: cachedResult.hasMore,
      });
      return;
    }

    this.setData({
      loading: true,
      isSearching: true,
      showSearchResult: true, // 确保设置为true
    });

    const page = isLoadMore ? this.data.page + 1 : 1;

    // 调用搜索API
    api
      .searchRecipes({
        keyword: this.data.searchKeyword,
        category: this.data.selectedCategory,
        page: page,
        pageSize: this.data.pageSize,
      })
      .then((res) => {
        if (res.code === 200 && res.data) {
          const list = res.data.list || [];
          const total = res.data.total || 0;
          const hasMore = this.data.pageSize * page < total;

          // 修正API返回数据中的图片路径
          const correctedList = list.map((item) => {
            // 如果是/images/recipes/路径，改为/images/discovers/png/
            if (item.imageUrl && item.imageUrl.includes("/images/recipes/")) {
              // 获取文件名（不含后缀）
              const fileName = item.imageUrl.split("/").pop().split(".")[0];

              // 根据搜索词或菜谱内容选择合适的图片
              let newImageName = "";
              if (
                item.title.includes("三明治") ||
                fileName.includes("sandwich") ||
                fileName.includes("healthy")
              ) {
                newImageName = "sanmingzhi.png";
              } else if (
                item.title.includes("蔬菜") ||
                item.title.includes("时蔬")
              ) {
                newImageName = "qingjiaoshishu.png";
              } else if (
                item.title.includes("排骨") ||
                item.title.includes("汤")
              ) {
                newImageName = "paigutang.png";
              } else if (item.title.includes("水果")) {
                newImageName = "shuiguoshala.png";
              } else if (
                item.title.includes("能量") ||
                item.title.includes("营养")
              ) {
                newImageName = "nengliangbang.png";
              } else {
                // 默认图片
                newImageName = "sanmingzhi.png";
              }

              return {
                ...item,
                imageUrl: `/images/discovers/png/${newImageName}`,
              };
            }
            return item;
          });

          // 更新搜索结果缓存
          const searchResultCache = { ...this.data.searchResultCache };
          searchResultCache[cacheKey] = {
            list: correctedList,
            page: page,
            hasMore: hasMore,
            timestamp: Date.now(),
          };

          this.setData({
            recipeList: isLoadMore
              ? [...this.data.recipeList, ...correctedList]
              : correctedList,
            page: page,
            hasMore: hasMore,
            showSearchResult: true,
            searchResultCache,
          });
        }
      })
      .catch((err) => {
        console.error("搜索菜谱失败:", err);
        // 使用模拟数据
        let imageUrl = "/images/discovers/png/sanmingzhi.png";
        const keyword = this.data.searchKeyword;

        // 根据搜索关键词选择合适的图片
        if (keyword.includes("三明治") || keyword.includes("面包")) {
          imageUrl = "/images/discovers/png/sanmingzhi.png";
        } else if (
          keyword.includes("蔬菜") ||
          keyword.includes("青菜") ||
          keyword.includes("素食")
        ) {
          imageUrl = "/images/discovers/png/qingjiaoshishu.png";
        } else if (keyword.includes("汤") || keyword.includes("排骨")) {
          imageUrl = "/images/discovers/png/paigutang.png";
        } else if (keyword.includes("水果") || keyword.includes("沙拉")) {
          imageUrl = "/images/discovers/png/shuiguoshala.png";
        } else if (keyword.includes("能量") || keyword.includes("营养")) {
          imageUrl = "/images/discovers/png/nengliangbang.png";
        } else if (keyword.includes("鱼") || keyword.includes("海鲜")) {
          imageUrl = "/images/discovers/png/qingzhengluyu.png";
        } else if (keyword.includes("饼干")) {
          imageUrl = "/images/discovers/png/binggan.png";
        } else if (keyword.includes("意面") || keyword.includes("意大利")) {
          imageUrl = "/images/discovers/png/yidalimina.png";
        }

        const mockList = [
          {
            id: 1,
            title: "健康" + this.data.searchKeyword + "食谱",
            imageUrl: imageUrl,
            description:
              "这是一道健康美味的" + this.data.searchKeyword + "菜品",
            calories: 300,
            cookingTime: "30分钟",
            difficulty: "简单",
            category: "健康菜",
          },
        ];

        this.setData({
          recipeList: isLoadMore
            ? [...this.data.recipeList, ...mockList]
            : mockList,
          page: page,
          hasMore: false,
          showSearchResult: true, // 确保设置为true
        });
      })
      .finally(() => {
        this.setData({
          loading: false,
          showSearchResult: true, // 最后再确保为true
        });
        wx.stopPullDownRefresh();
      });
  },

  // 重写上拉加载更多
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      if (this.data.showSearchResult) {
        this.searchRecipes(true);
      } else {
        this.getRecipeList(true);
      }
    }
  },

  // 清理过期缓存
  clearExpiredCache() {
    const now = Date.now();
    const searchResultCache = { ...this.data.searchResultCache };
    let hasExpired = false;

    // 清除超过10分钟的缓存
    Object.keys(searchResultCache).forEach((key) => {
      if (now - searchResultCache[key].timestamp > 10 * 60 * 1000) {
        delete searchResultCache[key];
        hasExpired = true;
      }
    });

    if (hasExpired) {
      this.setData({ searchResultCache });
    }
  },
});
